package com.soulkun.smarthome.ui.main.home

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.navGraphViewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayoutMediator
import com.google.zxing.integration.android.IntentIntegrator
import com.soulkun.smarthome.R
import com.soulkun.smarthome.databinding.AppFragmentMainHomeBinding
import com.soulkun.smarthome.logic.Constant
import com.soulkun.smarthome.logic.dto.StatusMessageDTO
import com.soulkun.smarthome.logic.enum.MessageCodeEnum
import com.soulkun.smarthome.logic.manager.BroadcastManager
import com.soulkun.smarthome.logic.vo.RoomDeviceVO
import com.soulkun.smarthome.ui.main.MainNavigationDataBindingFragment
import com.soulkun.smarthome.ui.main.home.dialog.AppMainHomeSpeechRecognitionDialog
import com.soulkun.smarthome.ui.main.home.popup.AppMainHomeAddPopupWindow
import com.soulkun.smarthome.ui.main.home.popup.AppMainHomeFamilyPopupWindow
import com.soulkun.smarthome.ui.main.home.viewmodel.AppMainHomeViewModel
import soulkun.library.mvvm.adapter.BaseObservableDataFragmentStateAdapter
import soulkun.library.utils.permission.PermissionUtils
import soulkun.library.utils.screen.ScreenUtils
import soulkun.library.utils.toast

class AppMainHomeFragment : MainNavigationDataBindingFragment<AppFragmentMainHomeBinding>() {

    private val viewModel by navGraphViewModels<AppMainHomeViewModel>(R.id.app_navigation_main_home)

    private var tabLayoutMediator: TabLayoutMediator? = null

    private val viewPager2OnPageChangeCallback by lazy {
        object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (viewModel.roomDeviceList.isNotEmpty()) {
                    viewModel.selectRoomLiveData.value = viewModel.roomDeviceList[position].room
                }
            }
        }
    }

    private val familyPopupWindow by lazy {
        AppMainHomeFamilyPopupWindow(mContext, this, viewModel).apply {
            setOnDismissListener {
                viewModel.maskShowStatus.set(false)
            }
        }
    }
    private val addPopupWindow by lazy {
        AppMainHomeAddPopupWindow(mContext) { popup ->
            View.OnClickListener {
                when (it.id) {
                    R.id.view_main_home_add_background_add_device -> {
                        if (PermissionUtils.fragmentCheckPermissionList(
                                this,
                                mContext,
                                listOf(Manifest.permission.CAMERA),
                                Constant.PERMISSION_REQUEST_CAMERA
                            )
                        ) {
                            startAddDeviceCamera()
                            popup.dismiss()
                        }
                    }
                }
            }
        }
    }

    private val statusBroadcastReceiver by lazy {
        BroadcastManager.SoulkunBroadcastReceiver(MessageCodeEnum.Status) {
            val statusMessageDTO = it as StatusMessageDTO
            viewModel.roomDeviceList.forEach(action = { roomDeviceVO ->
                roomDeviceVO.deviceList.filter { deviceInfoVO -> deviceInfoVO.id == statusMessageDTO.deviceId }
                    .forEach(action = { deviceInfoVO -> deviceInfoVO.online.set(statusMessageDTO.onlineStatus) })
            })
        }
    }

    override fun setLayout(): Int {
        return R.layout.app_fragment_main_home
    }

    override fun initView() {
        super.initView()
        ScreenUtils.setViewFitSystemWindows(requireDataBinding().root)
        requireDataBinding().vp2MainHomeSmartBanner.run {
            offscreenPageLimit = 1
            orientation = ViewPager2.ORIENTATION_HORIZONTAL
            adapter = object : FragmentStateAdapter(childFragmentManager, lifecycle) {
                override fun getItemCount(): Int {
                    return 1
                }
                override fun createFragment(position: Int): Fragment {
                    return AppMainHomeWeatherFragment()
                }
            }
//            setPageTransformer(MarginPageTransformer(15.toPx()))
        }
    }

    override fun initData() {
        requireDataBinding().lifecycleOwner = viewLifecycleOwner
        requireDataBinding().viewModel = viewModel
        requireDataBinding().onClickListener = View.OnClickListener {
            when (it.id) {
                R.id.view_main_home_background_family -> {
                    if (viewModel.familyList.isNotEmpty()) {
                        familyPopupWindow.showAtLocation(requireDataBinding().root, Gravity.TOP, 0, 0)
                    }
                }
                R.id.iv_main_home_icon_microphone -> {
                    if (PermissionUtils.fragmentCheckPermissionList(
                            this,
                            mContext,
                            listOf(
                                Manifest.permission.RECORD_AUDIO,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            ),
                            Constant.PERMISSION_REQUEST_RECORD_AUDIO
                        )
                    ) {
                        viewModel.getRoomDeviceCommandList(onComplete =  {
                            val speechRecognitionDialog = AppMainHomeSpeechRecognitionDialog()
                            speechRecognitionDialog.show(
                                childFragmentManager,
                                "SpeechRecognitionDialog"
                            )
                        }, onEmpty = {
                            "创建或加入家庭后才能使用语音识别".toast()
                        })
                    }
                }
                R.id.iv_main_home_icon_add -> {
                    if (viewModel.selectRoomLiveData.value == null) {
                        "创建家庭并完善房间信息后才能使用该功能".toast()
                    } else {
                        addPopupWindow.showAsDropDown(requireDataBinding().ivMainHomeIconAdd, 0, 0)
                    }
                }
            }
        }
        viewModel.getFamilyNameList(onComplete = {
            setFamilyViewPager2()
        }, onRoomEmpty = {
            setRoomEmptyViewPager2()
        })
    }

    override fun initListener() {
        requireDataBinding().vp2MainHomeListRoom.registerOnPageChangeCallback(
            viewPager2OnPageChangeCallback
        )
        BroadcastManager.registerBroadcast(
            mContext,
            MessageCodeEnum.Status,
            statusBroadcastReceiver
        )
    }

    override fun doOnCreate() {
    }

    override fun onDestroyView() {
        BroadcastManager.unregisterBroadcast(mContext, statusBroadcastReceiver)
        tabLayoutMediator?.detach()
        requireDataBinding().vp2MainHomeListRoom.unregisterOnPageChangeCallback(
            viewPager2OnPageChangeCallback
        )
        super.onDestroyView()
    }

    fun setFamilyViewPager2() {
        tabLayoutMediator = TabLayoutMediator(
            requireDataBinding().tlMainHomeTabRoom,
            requireDataBinding().vp2MainHomeListRoom
        ) { tab, position ->
            tab.text = viewModel.roomDeviceList[position].room.name
        }
        requireDataBinding().vp2MainHomeListRoom.run {
            offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
            adapter = BaseObservableDataFragmentStateAdapter<RoomDeviceVO>(
                childFragmentManager,
                lifecycle,
                viewModel.roomDeviceList
            ) {
                AppMainHomeRoomFragment(it, this@AppMainHomeFragment, viewModel)
            }
            tabLayoutMediator?.attach()
            currentItem = if (viewModel.selectRoomLiveData.value == null) {
                0
            } else {
                viewModel.roomDeviceList.indexOfFirst { it.room.id == viewModel.selectRoomLiveData.value!!.id }
                    .also {
                        if (it == -1) {
                            0
                        }
                    }
            }
        }
    }

    fun setRoomEmptyViewPager2() {
        tabLayoutMediator = TabLayoutMediator(
            requireDataBinding().tlMainHomeTabRoom,
            requireDataBinding().vp2MainHomeListRoom
        ) { _, _ ->
        }
        requireDataBinding().vp2MainHomeListRoom.run {
            offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
            adapter = object : FragmentStateAdapter(
                childFragmentManager,
                lifecycle
            ){
                override fun getItemCount(): Int {
                    return 1
                }

                override fun createFragment(position: Int): Fragment {
                    return AppMainHomeRoomEmptyFragment()
                }

            }
            tabLayoutMediator?.attach()
            currentItem = 0
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            Constant.PERMISSION_REQUEST_CAMERA -> {
                for (i in permissions.indices) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !shouldShowRequestPermissionRationale(
                                permissions[i]
                            )
                        ) { //如果用户拒接并选择不再询问
                            Snackbar.make(
                                requireDataBinding().root,
                                "请授权相机权限，否则无法扫描二维码添加设备",
                                Snackbar.LENGTH_LONG
                            )
                                .setAction(
                                    "前去设置"
                                ) { PermissionUtils.goToPermissionSettingPage(mContext) }
                                .show()
                            return
                        }
                    }
                }
                startAddDeviceCamera()
                addPopupWindow.dismiss()
            }
            Constant.PERMISSION_REQUEST_RECORD_AUDIO -> {
                for (i in permissions.indices) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !shouldShowRequestPermissionRationale(
                                permissions[i]
                            )
                        ) { //如果用户拒接并选择不再询问
                            Snackbar.make(
                                requireDataBinding().root,
                                "请授权录音权限，否则无法语音识别指令",
                                Snackbar.LENGTH_LONG
                            )
                                .setAction(
                                    "前去设置"
                                ) { PermissionUtils.goToPermissionSettingPage(mContext) }
                                .show()
                            return
                        }
                    }
                    viewModel.getRoomDeviceCommandList(onComplete =  {
                        val speechRecognitionDialog = AppMainHomeSpeechRecognitionDialog()
                        speechRecognitionDialog.show(
                            childFragmentManager,
                            "SpeechRecognitionDialog"
                        )
                    }, onEmpty = {
                        "创建或加入家庭后才能使用语音识别".toast()
                    })
                }
            }
        }
    }

    fun startAddDeviceCamera() {
        IntentIntegrator(mActivity).run {
            setPrompt("")
            setOrientationLocked(false)
            setCameraId(0)
            setBeepEnabled(true)
            captureActivity = AppMainHomeAddDeviceActivity::class.java
            startActivityForResult(createScanIntent().apply {
                putExtra(Constant.BUNDLE_ROOM, viewModel.selectRoomLiveData.value)
            }, Constant.ACTIVITY_REQUEST_ADD_DEVICE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            Constant.ACTIVITY_REQUEST_ADD_DEVICE -> {
                viewModel.getFamilyNameList(onComplete = {
                    setFamilyViewPager2()
                }, onRoomEmpty = {
                    setRoomEmptyViewPager2()
                })
            }
        }
    }


}